package site.addzero.repl

import kotlinx.coroutines.runBlocking
import org.koin.core.annotation.Single
import site.addzero.app.AdvancedRepl
import site.addzero.app.ParamDef
import site.addzero.cli.config.Lines
import site.addzero.cli.config.configService
import site.addzero.cli.dotfiles.sync_stragty.SyncUtil
import site.addzero.cli.setting.SettingContext.DOTFILES_DIR
import site.addzero.cli.setting.SettingContext.HOME_DIR
import site.addzero.cli.setting.SettingContext.absParamDescription
import site.addzero.util.AddFileUtil
import site.addzero.util.KoinInjector.inject
import site.addzero.util.SourcePathResolver
import site.addzero.util.StatusPrinter
import site.addzero.util.TargetPathResolver
import kotlin.reflect.typeOf


/**
 * AddCommand的REPL包装类，实现AdvancedRepl接口
 */
@Single
class AddDotFilesRepl : AdvancedRepl<AddDotFilesRepl.AddCommandParams, Unit> {
    override val command: String = "add-dotfiles"
    override val description: String
        get() = "添加文件到dotfiles"
    override val paramDefs: List<ParamDef> = listOf(
        ParamDef(
            name = "sourcePaths",
            type = typeOf<String>(),
            description = "要添加的文件路径(多个路径用逗号分隔,但是一个批次中要么绝对路径,要么相对家目录路径)"
        ),
        ParamDef(
            name = "abs",
            type = typeOf<Boolean>(),
            description = absParamDescription,
            defaultValue = false
        ),
    )

    data class AddCommandParams(
        val sourcePaths: String,
        val abs: Boolean = false,
    )

    override fun eval(params: AddCommandParams): Unit = runBlocking {
        val abs = params.abs
        val sourcePaths = params.sourcePaths.split(",").map { it.trim() }.filter { it.isNotEmpty() }
        val currentPlatformConfig = configService.currentPlatformConfig

        if (sourcePaths.isEmpty()) {
            System.err.println("未提供有效的文件路径")
            return@runBlocking
        }

        val sourcePathResolver = inject<SourcePathResolver>()
        val targetPathResolver = inject<TargetPathResolver>()

        var successCount = 0
        for (sourcePath in sourcePaths) {
            val newSourceDirAbs = sourcePathResolver.resolveSourcePath(sourcePath, abs)

            if (newSourceDirAbs == null) {
                System.err.println("dotfiles文件不存在: $sourcePath")
                continue
            }

            // 解析目标路径，保持文件在家目录中的相对结构
            val targetPath = targetPathResolver.resolveTargetPath(newSourceDirAbs)

            // 检查目标路径是否已经配置过
            val existingLink = currentPlatformConfig.links.find {
                it.source == newSourceDirAbs && it.target == targetPath
            }

            if (existingLink != null) {
                println("文件 ${newSourceDirAbs} 已经配置过，跳过添加")
                successCount++
                continue
            }

            println("开始创建软链接,${newSourceDirAbs} 到 ${targetPath}")

            AddFileUtil.mvln(newSourceDirAbs, targetPath)
            //提交配置
            val links = currentPlatformConfig.links
            val lines = links.plus(Lines(newSourceDirAbs, targetPath))
            val copy = currentPlatformConfig.copy(links = lines)
            configService.updatePlatFormConfig(copy)

            successCount++
            println("文件添加完成: $sourcePath")
        }

        if (successCount > 0) {
            // 上传配置
            SyncUtil.commitAndPush()
            println("成功添加 $successCount 个文件到dotfiles")
        } else {
            System.err.println("未能成功添加任何文件到dotfiles")
        }

        // 打印当前的软连接和同步软件包信息
        val statusPrinter = inject<StatusPrinter>()
        statusPrinter.printCurrentStatus()
    }

//    override fun createParams(values: List<Any?>): AddCommandParams {
//        return AddCommandParams(
//            sourcePaths = values[0] as String,
//            abs = values.getOrNull(1) as? Boolean ?: false,
//        )
//    }
}
